<template>
  <m-container class="print-code">
    <in-work-item :modal="modal" v-if="modal" />
    <view class="container">
      <u-section title="已绑定条码明细" :right="false" :show-line="false" color="#333">
        <template slot="right" v-if="modal.palletCodeSkuList">
          <view class="f12 c999" :class="{ active: modal.palletCodeSkuList.length }">
            {{ modal.palletCodeSkuList.length }}/{{ modal ? modal.packageQuantity : 0 }}
          </view>
        </template>
      </u-section>
      <template v-if="modal.palletCodeSkuList && modal.palletCodeSkuList.length">
        <in-work-code
          v-for="(item, index) in modal.palletCodeSkuList"
          :status-type="item.status ? barCodeStatusMap[item.status].type : 'primary'"
          :status-txt="item.status ? barCodeStatusMap[item.status].txt : '未入库'"
          :key="index"
          :modal="{ barcode: item.skuBarcode || item }"
          :show-minus="modal.status !== 2"
          :disabled="getIsDelDisabled(item)"
          @del="handleClickDel(index, item)"
        />
      </template>

      <m-empty v-else tip="还没有开始条码扫描操作哦!" />
    </view>

    <m-fixed v-if="modal && modal.status !== 2 && info.status !== 3">
      <view class="df aic jcsb">
        <m-button
          width="48.5%"
          type="primary"
          background="#00cfcf"
          size="xl"
          @click="handleClickScan(!enable)"
          :disabled="getDisabled"
        >
          {{ enable ? '关闭扫码' : '点击扫码' }}
        </m-button>
        <m-button width="48.5%" size="xl" @click="handleClickOver" :disabled="getScanOver" :loading="loading">
          扫码完成
        </m-button>
      </view>
    </m-fixed>
  </m-container>
</template>

<script>
const barcodeModel = uni.requireNativePlugin('iData-BarcodePlugin-BarcodeModule')
const globalEvent = uni.requireNativePlugin('globalEvent')
import { checkSkuBarcode } from '@/api/modules/in-work'
import { router } from '@/router'
import { showModal } from '@/hooks'
import deepClone from '@/utils/deep-clone'
import { isAppPlus } from '@/utils/platform'
import { mapState } from 'vuex'
import { barCodeStatusMap } from '@/utils/constant'

export default {
  data() {
    return {
      modal: null,
      back: 1,
      enable: false,
      index: 0,
      showModal: true,
      loading: false,
      type: 'fastInWork',
      barCodeStatusMap,
    }
  },
  computed: {
    ...mapState({
      info: (state) => state.inWork.info,
      form: (state) => state.inWork.form,
    }),
    getDisabled() {
      return this.modal.palletCodeSkuList?.length === this.modal?.packageQuantity || this.loading
    },
    getScanOver() {
      if (this.loading) {
        return true
      } else if (this.getIsSystem) {
        return (this.modal.palletCodeSkuList || []).every((item) => this.getIsDelDisabled(item))
      }
      return !this.getDisabled
    },
    getIsDelDisabled() {
      return (item) => item.status === 1 || !(typeof item === 'string')
    },
    getIsSystem() {
      return this.type === 'systemInWork'
    },
  },
  onUnload() {
    this.handleClickScan(false)
    this.modal = null
    barcodeModel.closeScan()
  },
  onBackPress(e) {
    if (
      e.from == 'navigateBack' ||
      !(this.showModal && this.modal.palletCodeSkuList?.length !== 0 && this.modal.status !== 2) ||
      this.getIsSystem
    ) {
      return false
    }

    showModal({
      title: '数据保存提示',
      content: '是否确认保存扫码数据？',
      showCancelButton: true,
      confirm: () => {
        this.submitData()
        this.showModal = false

        this.goBack()
      },
      cancel: () => {
        this.showModal = false
        this.goBack()
      },
    })
    return true
  },
  async onLoad(options) {
    this.index = this.info.imsStockInOrderDetailList.findIndex(
      (item) => item.inOrderDetailId == options.inOrderDetailId
    )

    this.type = options.type
    this.back = options.back
    this.initData()

    barcodeModel.initScan()
    globalEvent.addEventListener('iDataBarcodeEvent', async ({ barcode }) => {
      if (this.$Router.currentRoute.name !== 'ScanDetail' || this.modal === null) {
        return
      }

      const barcodes = this.info.imsStockInOrderDetailList
        .map((item) => item.palletCodeSkuList.map((item) => item.skuBarcode || item))
        .flat(1)
      const isHave = barcodes.some((item) => item === barcode)
      if (this.getIsSystem && isHave) {
        uni.showToast({
          title: barcode + '条码已存在或者已被使用',
          icon: 'none',
        })
        return
      }

      const res = await checkSkuBarcode([barcode])

      if (barcode.includes(this.modal.skuPartNo)) {
        const { unitWeight, palletCodeSkuList, grossWeight } = this.modal
        const arr = (palletCodeSkuList || []).filter((item) => {
          if (typeof item === 'string' || item.status === 0) {
            return true
          }
          return false
        })
        if (unitWeight < (arr.length + 1) * grossWeight) {
          showModal({
            title: '超重提示',
            content: '扫描条码已达到托盘承重最大值了，无需继续扫码！',
            confirmText: '我知道了',
          })
          this.handleClickScan(false)
          return
        }

        if (this.modal.palletCodeSkuList?.length < +this.modal.packageQuantity) {
          !this.isHaveCode(barcode) && this.modal.palletCodeSkuList.unshift(barcode)

          if (this.modal.palletCodeSkuList?.length === +this.modal.packageQuantity) {
            this.handleClickScan(false)
          }
        }
      } else {
        uni.showToast({
          title: '条码不匹配',
          icon: 'none',
        })
      }
    })
  },
  methods: {
    isHaveCode(barcode) {
      const barcodes = this.info.imsStockInOrderDetailList
        .map((item) => item.palletCodeSkuList.map((item) => item.skuBarcode || item))
        .flat(1)
      return barcodes.some((item) => item === barcode)
    },
    async goBack() {
      this.$Router.$lockStatus = false
      uni.navigateBack({
        delta: 1,
      })
    },
    async initData() {
      this.modal = this.info.imsStockInOrderDetailList[this.index]
      const palletCodeSkuList = deepClone(this.modal.palletCodeSkuList || [])

      this.modal.palletCodeSkuList = isAppPlus
        ? palletCodeSkuList
        : palletCodeSkuList.length
        ? palletCodeSkuList
        : new Array(this.modal.packageQuantity).fill(0).map(
            (item) =>
              this.modal.skuPartNo +
              '-28100011' +
              Math.floor(Math.random() * 1000000)
                .toString()
                .padStart(6, '0')
          )
    },
    handleClickDel(index, item) {
      if (this.getIsDelDisabled(item)) {
        uni.showToast({
          title: '条码已进行，已入库操作，等待AGV中不可进行移除操作!',
          icon: 'none',
        })
        return
      }

      showModal({
        title: '移除提示',
        content: '请问您确认要移除吗？',
        showCancelButton: true,
        confirm: () => {
          this.modal.palletCodeSkuList.splice(index, 1)
        },
      })
    },
    async handleClickScan(enable) {
      this.enable = enable
      if (this.enable) {
        barcodeModel.intervalSet('500', (ret) => {
          console.log('连续扫描开启', ret)
        })
      }

      barcodeModel.continueScan(this.enable, (ret) => {
        console.log('连续扫描关闭', ret)
      })
    },
    async submitData() {
      this.showModal = false

      const skuBarcodes = this.modal.palletCodeSkuList.filter((item) => typeof item === 'string')
      await this.$store.dispatch('inWork/setPalletCodeSkuAction', {
        ...this.info,
        palletCode: this.form.palletCode,
        ...this.modal,
        skuBarcodes,
        partNo: this.modal.skuPartNo,
      })
      await this.$store.dispatch('inWork/setUpdateWorkOrderStatusAction')
      return
    },
    async handleClickOver() {
      this.loading = true
      try {
        if (this.type === 'fastInWork') {
          await this.submitData()
        } else {
          this.modal.status = 1
        }
        this.$store.commit('inWork/setScanInOrderDetailId', this.modal.inOrderDetailId)
        uni.showToast({
          title: '操作成功',
          icon: 'none',
        })

        router.back(this.back)

        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.print-code {
  .container {
    padding: 20rpx;
    .active {
      color: #248dfa;
    }
  }
}
</style>
